package cmd

import (
	"errors"
	"fmt"
	"gexcel/pkg/excel"
	"gexcel/pkg/screen"
	"os"

	"github.com/spf13/cobra"
)

var Interactive bool
var rootFilePath string

func init() {
	rootCmd.Flags().BoolVarP(&Interactive, "interactive", "i", false, "是否使用交互模式")
}

var rootCmd = &cobra.Command{
	Use:   "gexcel",
	Short: "查看编辑表格内容",
	Args: func(cmd *cobra.Command, args []string) error {
		if len(args) == 0 {
			return errors.New("需要指定表格文件路径！")
		}
		if len(args) > 1 {
			return errors.New("暂时仅支持打开一个表格文件！")
		}
		rootFilePath = args[0]
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		if Interactive {
			e := excel.NewExcel(rootFilePath)
			defer func(e *excel.Excel) {
				_ = e.Close()
			}(e)
			s := screen.NewExcelScreen(e)
			s.Run()
		}
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		_, err := fmt.Fprintln(os.Stderr, err)
		if err != nil {
			return
		}
		os.Exit(1)
	}
}
